<?php
namespace App\Admin\Actions;
/**
 * 自定义表单弹出工具
 * 用法：$action->append(new LazyFormAction(OrderSendForm::class,
['id'=>$action->row->id],'订单发货','feather icon-clock'));
 * 自定义参数 在表单中通过 $this->data获取
 */

use App\Admin\Forms\OrderCancelForm;
use Dcat\Admin\Admin;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Grid\RowAction;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Modal;

class LazyFormAction  extends RowAction implements LazyRenderable
{
    use LazyWidget; // 使用异步加载功能

    protected $form;
    protected ?array $data=null;
    protected ?string $icon='';
    protected $title = '';

    /**
     * @param $form 表单类名
     * @param array|null $data 自定义参数
     * @param string|null $title 标题
     * @param string|null $icon 图标类名，例如：“feather icon-clock”
     */
    public function __construct( $form,?array $data=null,?string $title = null,?string $icon='feather icon-link')
    {
        parent::__construct($title);
        $this->form=$form;
        $this->data=$data;
        $this->icon=$icon;
        $this->title=$title;

    }

    public function render() {
        // 实例化表单类并传递自定义参数
        $data=$this->data?$this->data:json_decode($this->getRow(),true);
        try{
            $form = $this->form::make()->payload($this->data);
        }catch(\Exception $e){
            throw new \Exception("实例化表单失败，请检查{$this->form}是否存在，并实现 implements LazyRenderable");
        }
        $btn = '<span style="padding-right:10px" title="'.$this->title.'"><i class="'.$this->icon.'"></i><span class="actions-title">'.$this->title.'</span></span>';
        //修改操作栏在横排和下拉时的样式
        $css=<<<EOF
.actions-title{
    display:none;
    padding-left:4px;
}
.dropdown-item .actions-title{
    display:inline-block!important;
}
EOF;

        Admin::style($css);
        return Modal::make()
            ->lg()
            ->title($this->title)

            ->body($form)
            ->button($btn);
    }
}
